//
//  UICalendarViewController.m
//  baohebao
//
//  Created by ming wang on 12-2-25.
//  Copyright (c) 2012年 mingrui. All rights reserved.
//

#import "UICalendarViewController.h"


@implementation UICalendarViewController

@synthesize  calendarView,weekView,table,arr,allArr,current_Day;//,dayArr,fullDayArr;
-(int)getDayCountOfaMonth:(CFGregorianDate)date{
	switch (date.month) {
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			return 31;
			
		case 2:
			if((date.year % 4==0 && date.year % 100!=0) || date.year % 400==0)
				return 29;
			else
				return 28;
		case 4:
		case 6:
		case 9:		
		case 11:
			return 30;
		default:
			return 31;
	}
}


-(void)movePrevMonth{
        [MyClass getInstance].touchPoint = CGPointMake(0, 0);
    if (ViewState==1) {
        self.current_Day = [[NSDate alloc] initWithTimeInterval:(-24 * 60 * 60) sinceDate:current_Day];
        
        //正常情况下减一天
        if (dayViewCurDate.day > 1) {
            dayViewCurDate.day -= 1;
        }
        else //某个月的第一天，减去后会到上一个月
        {
            //不是第一个月的第一天，减去后会到上一个月的最后一天
            if (dayViewCurDate.month>1) {
                dayViewCurDate.month -= 1;
                dayViewCurDate.day = [self getDayCountOfaMonth:dayViewCurDate];
            }
            else //第一个月的第一天，减去后会到去年的最后一天
            {
                dayViewCurDate.year -= 1;
                dayViewCurDate.month = 12;
                dayViewCurDate.day = 31;
            }
        }
        
        [self showDayView];
        //[self reloadNav];
    }
    else if(ViewState==2)
    {
        [self.weekView movePrevMonth];
        [self reloadNav];
        self.arr=nil;
        [self.table reloadData];
    }
    else if(ViewState==3){
        [self.calendarView movePrevMonth];
        [self reloadNav];
        self.arr=nil;
        [self.table reloadData];
    }
    else if(ViewState==4){
    
    }
    
}
-(void)moveNextMonth{
        [MyClass getInstance].touchPoint = CGPointMake(0, 0);
    if (ViewState==1) {
        self.current_Day = [[NSDate alloc] initWithTimeInterval:(24 * 60 * 60) sinceDate:current_Day];
        
        int daysOfMonth = [self getDayCountOfaMonth:dayViewCurDate];
        
        //正常情况下加一天
        if (daysOfMonth > dayViewCurDate.day) {
            dayViewCurDate.day += 1;
        }
        else //某个月的最后一天，加后会到下一个月的第一天
        {
            //不是最后一个月的最后一天，加后会到下一个月的第一天
            if (dayViewCurDate.month < 12) {
                dayViewCurDate.month += 1;
                dayViewCurDate.day = 1;
            }
            else //最后一个月的最后一天，加后会到明年的第一天
            {
                dayViewCurDate.year += 1;
                dayViewCurDate.month = 1;
                dayViewCurDate.day = 1;
            }
        }
        
        [self showDayView];
        //[self reloadNav];
    }
    else if(ViewState==2)
    {
        [self.weekView moveNextMonth];
        [self reloadNav];
        self.arr=nil;
        [self.table reloadData];
    }
    else if(ViewState==3){
        [self.calendarView moveNextMonth];
        [self reloadNav];
        self.arr=nil;
        [self.table reloadData];
    }
    else if(ViewState==4){
        
    }
} 
- (void) selectWeekDateChanged:(CFGregorianDate) selectDate{
    NSString* strDate=[NSString stringWithFormat:@"%04d%02d%02d",selectDate.year,selectDate.month,selectDate.day];
    self.arr = [self.weekView getDayFlag:strDate];
    [table reloadData];
}
- (void) WeekChanged:(CFGregorianDate) currentMonth viewLeftTop:(CGPoint)viewLeftTop height:(float)height{

}
- (void) beforeWeekChange:(TWeekView*) calendarView willto:(CFGregorianDate) currentMonth{

}
-(void)initDisplayToday{
    CFGregorianDate currentMonthDate=CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(),CFTimeZoneCopyDefault());
    NSString* strDate=[NSString stringWithFormat:@"%04d%02d%02d",currentMonthDate.year,currentMonthDate.month,currentMonthDate.day];
    self.allArr = [self.calendarView getDayFlag:strDate];
    [self setDisplayArr];
}
- (void) monthChanged:(CFGregorianDate) currentMonth viewLeftTop:(CGPoint)viewLeftTop height:(float)height{
    calendarView.frame= CGRectMake(viewLeftTop.x, viewLeftTop.y, calendarView.frame.size.width, height);
    table.frame = CGRectMake(0, viewLeftTop.y+height, 320, 480-20-44-44-height);
    self.allArr = nil;
    [self setDisplayArr];
}
- (void) beforeMonthChange:(TdCalendarView*) calendarView willto:(CFGregorianDate) currentMonth{
   
}
- (void) selectDateChanged:(CFGregorianDate) selectDate{
    NSString* strDate=[NSString stringWithFormat:@"%04d%02d%02d",selectDate.year,selectDate.month,selectDate.day];
    self.allArr = [self.calendarView getDayFlag:strDate];
    [self setDisplayArr];
}
-(void)reloadNav{
    for(UIView *subview in [self.navigationController.view  subviews]){
        if (subview.tag==9999)
            [subview removeFromSuperview];
	}
    
    const CGFloat kChangeMonthButtonWidth = 46.0f;
    const CGFloat kChangeMonthButtonHeight = 30.0f;
    const CGFloat kHeaderVerticalAdjust = 26.f;
    CGRect previousMonthButtonFrame = CGRectMake(0,
                                                 kHeaderVerticalAdjust,
                                                 kChangeMonthButtonWidth,
                                                 kChangeMonthButtonHeight);
    UIButton *previousMonthButton = [[UIButton alloc] initWithFrame:previousMonthButtonFrame];
    [previousMonthButton setImage:[UIImage imageNamed:@"kal_left_arrow.png"] forState:UIControlStateNormal];
    previousMonthButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    previousMonthButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    [previousMonthButton addTarget:self action:@selector(movePrevMonth) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.view addSubview:previousMonthButton];
    previousMonthButton.tag = 9999;
    [previousMonthButton release];
    NSString* str;
    if (ViewState==1) {
//        //实例化一个NSDateFormatter对象
//        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//        //设定时间格式,这里可以设置成自己需要的格式
//        [dateFormatter setDateFormat:@"MM月dd日"];
//        //用[NSDate date]可以获取系统当前时间
//        str = [dateFormatter stringFromDate:current_Day];
//        [dateFormatter release];
        str = [NSString stringWithFormat:@"%d月%d日", dayViewCurDate.month, dayViewCurDate.day];
    }
    else if (ViewState==2) 
        str= [self.weekView getStrDate];
    else if (ViewState==3) 
        str= [self.calendarView getStrDate];
    else
        str = @"列表视图";
    CGSize size = CGSizeMake(320,2000);
    NSInteger fontSize;
    if (ViewState==2)
        fontSize = 19;
    else
        fontSize = 20;
    
    CGSize labelsize = [str sizeWithFont:[UIFont boldSystemFontOfSize:fontSize] constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
    
    CGRect monthLabelFrame = CGRectMake(0 + kChangeMonthButtonWidth,
                                        kHeaderVerticalAdjust+5,
                                        labelsize.width,
                                        17.f);
    headerTitleLabel = [[UILabel alloc] initWithFrame:monthLabelFrame];
    headerTitleLabel.backgroundColor = [UIColor clearColor];
    headerTitleLabel.font = [UIFont boldSystemFontOfSize:fontSize];
    headerTitleLabel.textColor = [UIColor whiteColor];
    [headerTitleLabel setText:str];
    headerTitleLabel.tag = 9999;
    [self.navigationController.view addSubview:headerTitleLabel];
    
    CGRect nextMonthButtonFrame = CGRectMake(0 + kChangeMonthButtonWidth + headerTitleLabel.frame.size.width,
                                             kHeaderVerticalAdjust,
                                             kChangeMonthButtonWidth,
                                             kChangeMonthButtonHeight);
    nextMonthButton = [[UIButton alloc] initWithFrame:nextMonthButtonFrame];
    [nextMonthButton setImage:[UIImage imageNamed:@"kal_right_arrow.png"] forState:UIControlStateNormal];
    nextMonthButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    nextMonthButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    [nextMonthButton addTarget:self action:@selector(moveNextMonth) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.view addSubview:nextMonthButton];
    nextMonthButton.tag = 9999;
    
    UIButton* goToday= [[UIButton alloc] initWithFrame:CGRectMake(210, kHeaderVerticalAdjust, 55, 30)];
    [goToday setTitle:@"回今天" forState:UIControlStateNormal];
    goToday.titleLabel.font = [UIFont systemFontOfSize:16];
    goToday.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    goToday.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    [goToday addTarget:self action:@selector(goToday) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.view addSubview:goToday];
    goToday.tag = 9999;
    
    
    UIBarButtonItem *ButtonItemAction = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemAction) target:self action:@selector(ContactAction)];   
    self.navigationItem.rightBarButtonItem = ButtonItemAction;
    ButtonItemAction.tag = 9999;
    [ButtonItemAction release];
    
}
-(void) ContactAction{
    [self CreateClearBackBtn];
    UIBigCustomView* MenuView = [[UIBigCustomView alloc] initWithFrame:CGRectMake(65, 65, 250, 190) choose:chooseNumber];
    [self.navigationController.view addSubview:MenuView];
    MenuView.tag = MENUVIEW_TAG;
    [MenuView set_Delegate:self];
    [MenuView release];     
}
- (void) CreateClearBackBtn{
    UIButton* backgroundBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
    [backgroundBtn addTarget:self action:@selector(hideMenu) forControlEvents:UIControlEventTouchUpInside]; 
    backgroundBtn.backgroundColor = [UIColor clearColor];
    backgroundBtn.tag = MENUVIEW_TAG;
    [self.navigationController.view addSubview:backgroundBtn];
    [backgroundBtn release];
}
-(void) hideMenu{
    for(UIView* u in self.navigationController.view.subviews){
        if (u.tag == MENUVIEW_TAG) {
            [u removeFromSuperview];
        }
    }
}
- (void) setDisplayArr{
    NSMutableArray* tmpArray = [[NSMutableArray alloc] init];
    self.arr = tmpArray;
    [tmpArray release];
    
    NSString* scheduleTypeStr = [MyClass getInstance].scheduleTypeStr;
    
    for(NSDictionary* dict in self.allArr) 
    {
        NSString * type = [dict objectForKey:@"type"];
        if ([MyClass getInstance].scheduleType == EScheduleType_all) {
            self.arr = self.allArr;
        }
        else
        {
            if ([type isEqualToString:scheduleTypeStr]) {
                [self.arr addObject:dict];
            }
        }
    }
    
    [table reloadData];
}
-(void) showDayView{
    ViewState=1;
    for (UIView* view in self.view.subviews) {
        if (view.tag==10000) {
            [view removeFromSuperview];
        }
    }
//    [dayArr removeAllObjects];
//    [fullDayArr removeAllObjects];
    NSMutableDictionary *FlagArray;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Chongqing"]];
    NSString* strDate1=[NSString stringWithFormat:@"%4d-%2d-%2d 00:00:01",dayViewCurDate.year,dayViewCurDate.month,dayViewCurDate.day];
    NSString* strDate2=[NSString stringWithFormat:@"%4d-%2d-%2d 23:59:59",dayViewCurDate.year,dayViewCurDate.month,dayViewCurDate.day];
    NSDate *date1 = [dateFormatter dateFromString:strDate1];
    NSDate *date2 = [dateFormatter dateFromString:strDate2];

    //date1 = [[NSDate alloc] initWithTimeInterval:(8 * 60 * 60) sinceDate:date1];
    //date2 = [[NSDate alloc] initWithTimeInterval:(8 * 60 * 60) sinceDate:date2];
    [dateFormatter release];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    NSDictionary * ret = [[MyClass getInstance] getSchedule:date1 toTime:date2];
    //NSArray * tmpArray;
    if ([[ret objectForKey:@"code"] intValue]==0) {
        if ([ret objectForKey:@"size"] > 0) {
            FlagArray = [ret objectForKey:@"list"];
        }        
        self.allArr = [[FlagArray allValues] objectAtIndex:0];
    }
    [self setDisplayArr];
//    NSMutableArray* tmpArr=[[NSMutableArray alloc] init];
//    for (NSMutableDictionary *dict in arr) {
//        NSDate * beginTime = [dict objectForKey:@"begin"];  
//        NSDate * endTime = [dict objectForKey:@"end"]; 
//        double tmpDouble = [date1 timeIntervalSinceDate:beginTime];
//        double tmp = [date2 timeIntervalSinceDate:endTime];
//        if ((tmpDouble>=0) &&(tmp>=0)) {
//            [self.fullDayArr addObject:dict];//这是全天计划
//        }
//        else
//        {
//            [tmpArr addObject:dict];
//        }
//    }
//    if ([tmpArr count]>0) {//如果大于零，那就查找复合对象，即该日程对象的起止时间包含了其他的日程对象
//        for (int i=0; i<=[tmpArr count]-1;i++) {
//            NSMutableDictionary *dict = [tmpArr objectAtIndex:i];
//            NSDate * beginTime = [dict objectForKey:@"begin"];  
//            NSDate * endTime = [dict objectForKey:@"end"]; 
//            NSString * refId = [dict objectForKey:@"refId"];
//            if (i==0) {
//                [dayArr removeAllObjects];
//            }
//            for (int j=0; j<=[tmpArr count]-1;j++) {
//                NSMutableDictionary *subdict = [tmpArr objectAtIndex:j];
//                NSString * subRefId = [subdict objectForKey:@"refId"];
//                if ([subRefId isEqualToString:refId]) {
//                    continue;
//                }
//                
//                NSDate * subBeginTime = [subdict objectForKey:@"begin"];  
//                NSDate * subEndTime = [subdict objectForKey:@"end"]; 
//                if ([endTime timeIntervalSince1970] <= [subBeginTime timeIntervalSince1970]) {
//                    [dict setObject:subEndTime forKey:@"end"];
//                    [dayArr addObject:dict];
//                    [tmpArr removeObject:subdict];
//                    i=0;
//                    break;
//                }
//                else if([subBeginTime timeIntervalSince1970] >= [beginTime timeIntervalSince1970])
//                {
//                    [dict setObject:subBeginTime forKey:@"beginTime"];
//                    [dayArr addObject:dict];
//                    [tmpArr removeObject:subdict];
//                    i=0;
//                    break;   
//                }
//                else
//                    [dayArr addObject:dict];
//                
//            }
//        }
//        
//    }
    table.frame= CGRectMake(0, 0, 320, 226+140);
    [table reloadData];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    chooseNumber = 11;  
    [self reloadNav];
    [table reloadData];    
}
-(void) showWeekView{
    ViewState=2;
    for (UIView* view in self.view.subviews) {
        if (view.tag==10000) {
            [view removeFromSuperview];
        }
    }
    for (UIView *subview in table.subviews) {
        if (subview.tag >= 1002)              
            [subview removeFromSuperview];
    }
    weekView=nil;
    calendarView=nil;
    if (!weekView) {
        weekView = [[TWeekView alloc]initWithFrame:CGRectMake(0, 0, 320, 50)]; 
        table.frame= CGRectMake(0, 50, 320, 226+140-44);
    }
    [self.view addSubview:weekView];
    weekView.backgroundColor = [UIColor whiteColor];
    weekView.weekViewDelegate = self;
    weekView.tag = 10000;
    [weekView release]; 
    chooseNumber = 21;  
    [self reloadNav];
    self.arr = nil;
    [table reloadData];
}
-(void) showMonthView{
    for (UIView *subview in table.subviews) {
        if (subview.tag >= 1002)              
            [subview removeFromSuperview];
    }
    ViewState=3;
    for (UIView* view in self.view.subviews) {
        if (view.tag==10000) {
            [view removeFromSuperview];
        }
    }
    weekView=nil;
    calendarView=nil;
    if (!calendarView) {
        NSInteger height;
        calendarView = [[TdCalendarView alloc]initWithFrame:CGRectMake(0, 0, 320, 190)];
        height = [calendarView getHeight];
        calendarView.frame = CGRectMake(0, 0, 320,height);
        table.frame= CGRectMake(0, height, 320, 226);
    }
    [self.view addSubview:calendarView];
    calendarView.backgroundColor = [UIColor whiteColor];
    calendarView.calendarViewDelegate = self;
    calendarView.tag = 10000;
    //[calendarView getSchedule];
    [calendarView release]; 
    chooseNumber = 31;  
    [self reloadNav];
    [table reloadData];
}
-(void) showListView{
    for (UIView *subview in table.subviews) {
        if (subview.tag >= 1002)              
            [subview removeFromSuperview];
    }
    ViewState=4;
    for (UIView* view in self.view.subviews) {
        if (view.tag==10000) {
            [view removeFromSuperview];
        }
    }
    CFGregorianDate currentDate;
	CFAbsoluteTime	currentTime;
    NSMutableDictionary *FlagArray;
    currentTime=CFAbsoluteTimeGetCurrent();
	currentDate=CFAbsoluteTimeGetGregorianDate(currentTime,CFTimeZoneCopyDefault());
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Chongqing"]];
    NSString* strDate1=[NSString stringWithFormat:@"%4d-%2d-%2d 00:00:01",currentDate.year,currentDate.month,currentDate.day];

    NSDate *date1 = [dateFormatter dateFromString:strDate1];
    date1 = [[NSDate alloc] initWithTimeInterval:(8 * 60 * 60) sinceDate:date1];
    NSDate *date2 = [[NSDate alloc] initWithTimeInterval:((8+240) * 60 * 60) sinceDate:date1];//取10天的信息，要再增加，就是改240那个了
    [dateFormatter release];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    NSDictionary * ret = [[MyClass getInstance] getSchedule:date1 toTime:date2];
    NSArray * keys;
    if ([[ret objectForKey:@"code"] intValue]==0) {
        if ([ret objectForKey:@"size"] > 0) {
            FlagArray = [ret objectForKey:@"list"];
        }
        keys =[[FlagArray allKeys] sortedArrayUsingSelector:@selector(compare:)];
        if (self.allArr) {
            [arr removeAllObjects];
        }
        else
        {
            self.allArr = [[[NSMutableArray alloc] init] autorelease]; 
        }
        for (NSString* str in keys) {
           [self.allArr addObjectsFromArray: [FlagArray objectForKey:str]];
        }
    }
    [self setDisplayArr];
    table.frame= CGRectMake(0, 0, 320, 226+140+50);
    [table reloadData];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    chooseNumber = 41; 
    [self reloadNav];
    [table reloadData];
    
}
-(void) ChangeView :(NSInteger) viewNum{
    CFGregorianDate initSelectDate;
    initSelectDate.year = 0;
    [MyClass getInstance].selectDate = initSelectDate;
    [MyClass getInstance].touchPoint = CGPointMake(0, 0);
    switch (viewNum) {
        case 1: 
            chooseNumber=11;
            self.current_Day = [NSDate date];
            dayViewCurDate=CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(),CFTimeZoneCopyDefault());
            [self showDayView];
            break;
        case 2: 
            if (chooseNumber !=21){
                [MyClass getInstance].touchPoint = CGPointMake(0, 0);
            }
            chooseNumber=21;
            [self showWeekView];
            break;
        case 3:
            if (chooseNumber !=31){
                [MyClass getInstance].touchPoint = CGPointMake(0, 0);
            }
            chooseNumber=31;
            [self showMonthView];
            break;
        case 4: 
            chooseNumber=41;
            [self showListView];
            break;
        default:
            break;
    }
}
-(void) NeedDisplyaView :(NSInteger) viewNum{
    switch (viewNum) {
        case 1: 
            [self setDisplayArr];
            break;
        case 2: 
            self.allArr = nil;
            [self setDisplayArr];
            [weekView setNeedsDisplay];
            break;
        case 3:
            self.allArr = nil;
            [self setDisplayArr];
            [calendarView setNeedsDisplay];
            break;
        case 4: 
            [self setDisplayArr];
            break;
        default:
            break;
    }
}
-(void)goToday{
    if (ViewState==1) {
        self.current_Day = [NSDate date];
        dayViewCurDate=CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(),CFTimeZoneCopyDefault());
        [self showDayView];
    }
    if (ViewState==2) {
        [weekView goTaday];
    }
    else if(ViewState==3)
        [calendarView goTaday];
    [self reloadNav];
}
-(void)ChooseWithFlagNumber:(NSInteger) Flag{
    [self hideMenu];
    if (Flag > 100) {
        chooseNumber= Flag/10; 
        if (ViewState==2) {
            [weekView goTaday];
        }
        else if(ViewState==3)
            [calendarView goTaday];
        [self reloadNav];
    }
    else
        chooseNumber= Flag;
    NSInteger flag1,flag2;
    flag1 = chooseNumber / 10;
    flag2 = chooseNumber % 10;
    switch (flag1) {
        case 1:
            if (ViewState!=1)
            {
                [self ChangeView:1];
                return;
            }
            break;
        case 2:
            if (ViewState!=2)
            {
                [self ChangeView:2];
                return;
            }
            break;
        case 3:
            if (ViewState!=3)
            {
                [self ChangeView:3];
                return;
            }
            break;
        case 4:
            if (ViewState!=4)
            {
                [self ChangeView:4];
                return;
            }
            break;
        default:
            break;
    }
    MyClass* myClass = [MyClass getInstance];
    switch (flag2) {
        case 1:
            myClass.scheduleType=EScheduleType_all;
            myClass.scheduleTypeStr = @"all";
            break;
        case 2:
            myClass.scheduleType=EScheduleType_plan;
            myClass.scheduleTypeStr = @"plan";
            break;
        case 3:
            myClass.scheduleType=EScheduleType_deed;
            myClass.scheduleTypeStr = @"deed";
            break;
        case 4:
            myClass.scheduleType=EScheduleType_birthday;
            myClass.scheduleTypeStr = @"birthday";
            break;
        case 5:
            myClass.scheduleType=EScheduleType_payday;
            myClass.scheduleTypeStr = @"payday";
            break;
        case 6:
            myClass.scheduleType=EScheduleType_activity;
            myClass.scheduleTypeStr = @"activity";
            break;
        default:
            break;
    }
    [self NeedDisplyaView:flag1];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        isFirst = YES;
        ViewState = 3;
        [self showMonthView];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

// Implement loadView to create a view hierarchy programmatically, without using a nib.

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    ViewState = 3;
    table = [[UITableView alloc] initWithFrame:CGRectMake(0, 190, 320, 226)];
	table.autoresizingMask = (UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight);
	table.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
	table.delegate = self;
	table.dataSource = self;
	[self.view addSubview:table];
    [table release];
    UISwipeGestureRecognizer *recognizer;
    
    recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [[self view] addGestureRecognizer:recognizer];
    [recognizer release];
    
    recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];
    [[self view] addGestureRecognizer:recognizer];
    [recognizer release];
    
    [super viewDidLoad];
//    dayArr = [[NSMutableArray alloc] init];
//    fullDayArr = [[NSMutableArray alloc] init];
    // Do any additional setup after loading the view from its nib.
}
-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer {
    if (recognizer.direction == UISwipeGestureRecognizerDirectionLeft) {
        [self moveNextMonth];
    }
    else if (recognizer.direction == UISwipeGestureRecognizerDirectionRight) {
        [self movePrevMonth ];
    }
}
-(UITableViewCell*)tableView:(UITableView *)tableView
       cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString  *CellIdentifier = @"CellIdentifier";
	UITableViewCell		*cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	
	if (nil == cell) {
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle 
                                       reuseIdentifier: CellIdentifier ] autorelease];
        cell.showsReorderControl = YES;
	}
    
    for (UIView *subview in cell.subviews) {
        if (subview.tag == 1001)              
            [subview removeFromSuperview];
    }
    cell.detailTextLabel.text=@"";
    cell.textLabel.text=@"";
	NSUInteger row = [indexPath row];
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
//    if (ViewState==1) {
//        cell.selectionStyle =  UITableViewCellSelectionStyleNone;
//        cell.textLabel.text=[NSString stringWithFormat:@"%2d:00",row];  
//        cell.imageView.image=nil;
//        for (NSDictionary *dict in self.arr) {
//            NSDate * beginTime = [dict objectForKey:@"begin"];  
//            NSDate * endTime = [dict objectForKey:@"end"]; 
//            NSDateFormatter *format = [[NSDateFormatter alloc] init];
//            NSLocale *enLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh-CN"];
//            [format setLocale:enLocale];
//            [enLocale release];
//            [format setDateFormat:@"HH,mm"];
//            //NSDate *dateTime = [format dateFromString:message];
//            NSString * dateString1 = [format stringFromDate:beginTime];
//            NSArray *timeArr;
//            timeArr = [dateString1 componentsSeparatedByString:@","];
//            NSInteger inth,intm;
//            inth = [[timeArr objectAtIndex:0] intValue];
//            intm = [[timeArr objectAtIndex:1] intValue];
//            UIButton * btn=nil;
//            if (inth == row ) {
//                NSString * refId = [dict objectForKey:@"refId"];
//                NSLog(@"refId is %@",refId);
//                for (UIView *subview in tableView.subviews) {
//                    if (subview.tag == 1002+[refId intValue])              
//                        btn = (UIButton*)subview;
//                }
//                if (!btn){
//                    btn = [UIButton buttonWithType:UIButtonTypeCuƒΩstom];
//                    btn.tag=1002+[refId intValue];
//                    NSLog(@"btn's tag is %d",btn.tag);
//                    double timeLength;
//                    timeLength = [endTime timeIntervalSinceDate:beginTime]/60;
//                    if ( timeLength> 0)
//                        btn.frame = CGRectMake(80, intm+row*60+44, 220, timeLength);
//                    else
//                        btn.frame = CGRectMake(80, intm+row*60+44, 220, 30); 
//                    btn.layer.cornerRadius = 10;/////////////////////////自己试着改变这个值，看看各个不同的效果。现在的设置是画了个圆圈。
//                    btn.layer.masksToBounds = YES;//////////////////////////  
//                    NSString *strType = [dict objectForKey:@"type"]; 
//                    if ([strType isEqualToString:@"plan"]) {
//                        btn.backgroundColor=[UIColor colorWithRed:216.0/255 green:156.0/255 blue:193.0/255 alpha:1.0]; 
//                    }
//                    else if ([strType isEqualToString:@"deed"])
//                        btn.backgroundColor=[UIColor blueColor];
//                    else if ([strType isEqualToString:@"manyObj"])
//                        btn.backgroundColor=[UIColor greenColor];
//                    btn.alpha = 0.6;
//                    [btn setTitle:[dict objectForKey:@"name"] forState: UIControlStateNormal] ;
//                    [tableView addSubview:btn];
//                }
//                else
//                {
//                
//                }
//            }
//            [format release];
//            
//        }
//        
//    }
//    else if (ViewState>1)
    {
        NSDictionary* dict = [self.arr objectAtIndex:row];
        if (dict)
        {
            NSDate * beginTime = [dict objectForKey:@"begin"];
            NSDate * endTime = [dict objectForKey:@"end"];
//            NSString * personMark = [dict objectForKey:@"personMark"];
//            NSString * personShowName = [dict objectForKey:@"personShowName"];
//            NSString * refId = [dict objectForKey:@"refId"];	
            NSString * name;
            NSString * type = [dict objectForKey:@"type"];
            NSString * given = [dict objectForKey:@"given"];
            if ([type isEqualToString:@"plan"] || [type isEqualToString:@"deed"])
            {
                if ([given isEqualToString:@"true"]) {
                    NSString* tmp;
                    if ([[dict objectForKey:@"personShowName"] length]>6) {
                        NSRange rage;
                        rage.length=6;
                        rage.location=0;
                        tmp=[tmp substringWithRange:rage];
                        tmp= [NSString stringWithFormat:@"%@...",tmp];
                        name =[NSString stringWithFormat:@"%@/%@" ,[dict objectForKey:@"name"],tmp]; 
                    }
                    else
                      name =[NSString stringWithFormat:@"来自%@的%@" ,[dict objectForKey:@"personShowName"],[dict objectForKey:@"name"]];   
                   
                }
                else
                name =[NSString stringWithFormat:@"%@的%@",[dict objectForKey:@"personShowName"] ,[dict objectForKey:@"name"]];
            }
            else
            {
                name = [dict objectForKey:@"name"];
            }
            cell.textLabel.font= [UIFont boldSystemFontOfSize:16];            
            if ([name length]>12) {
                NSRange rage;
                rage.length=12;
                rage.location=0;
                name=[name substringWithRange:rage];
                name= [NSString stringWithFormat:@"%@...",name];
//                CGSize size = CGSizeMake(180,20);
//                CGSize labelsize = [name sizeWithFont:[UIFont boldSystemFontOfSize:16] constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
            }
            [cell textLabel].text = name;
            
            NSDateFormatter *format = [[NSDateFormatter alloc] init];
            NSLocale *enLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh-CN"];
            [format setLocale:enLocale];
            [enLocale release];
            if (ViewState<4)
                [format setDateFormat:@"HH:mm"];
            else
                [format setDateFormat:@"MM月dd HH:mm"];
            //NSDate *dateTime = [format dateFromString:message];
            NSString * dateString1 = [format stringFromDate:beginTime];
            NSString * dateString2 = [format stringFromDate:endTime];
            [format release];
            if (ViewState<4){
                UILabel* lab1; 
                lab1 = [[UILabel alloc] init];
                lab1.frame = CGRectMake(240, 15, 80, 14);
                lab1.font = [UIFont systemFontOfSize:12];
                [lab1 setTextColor:[UIColor redColor]];
                lab1.text = [NSString stringWithFormat:@"%@-%@" ,dateString1,dateString2];
                lab1.backgroundColor = [UIColor clearColor];           
                lab1.tag = 1001;
                [cell addSubview:lab1];
                [lab1 release];
            }
            else
            {
                cell.detailTextLabel.text = [NSString stringWithFormat:@"%@-%@" ,dateString1,dateString2];
            }
            BOOL isPink=NO;
            BOOL isBlue=NO;
            BOOL isBrown=NO;
            BOOL isOrange=NO;
            BOOL isGreen=NO;
            if ([type isEqualToString:@"plan"] && !isPink)
            {
                cell.imageView.image =  [UIImage imageNamed:@"pink.png"] ;
            }
            else if ([type isEqualToString:@"deed"] && !isBlue)
            {
                isBlue=YES;
                cell.imageView.image = [UIImage imageNamed:@"blue.png"];
                
            }
            else if ([type isEqualToString:@"birthday"]&& !isGreen)
            {
                isGreen =YES;
                cell.imageView.image = [UIImage imageNamed:@"green.png"];  
            }
            else if ([type isEqualToString:@"payday"]&& !isOrange)
            {
                isOrange= YES;
                cell.imageView.image = [UIImage imageNamed:@"orange.png"];
                
            }
            else if ([type isEqualToString:@"activity"]&& !isBrown)
            {
                isBrown= YES;
                cell.imageView.image = [UIImage imageNamed:@"brown.png"];
            }
        }
    }

	return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (ViewState==1) {
        return 44;//;[[arr objectAtIndex:indexPath.row] count]*44;
    }
    else
        return 44;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    if (ViewState==1) 
//        return 24+[fullDayArr count];
//    else
        return [arr count];
}


-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if (ViewState==1) {
        [self showDayView];
    }
    else if (ViewState==2) 
    {
        [weekView movePrevNext:100];        
        [weekView touchAtDate: [MyClass getInstance].touchPoint];
    }
    else if (ViewState==3) 
    {
        if (!isFirst) 
        {
            [calendarView movePrevNext:100];
            [calendarView touchAtDate: [MyClass getInstance].touchPoint];
        }else 
        {
             isFirst = NO;
        }
    }
    else if (ViewState==4) 
    {
        [self showListView];
    }
    [self reloadNav];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(ViewState>=1)
    {
        NSDictionary* dict = [self.arr objectAtIndex:indexPath.row];
        if (dict)
        {
            NSString * type = [dict objectForKey:@"type"];
            NSString * refId = [dict objectForKey:@"refId"];
            NSString * personMark = [dict objectForKey:@"personMark"];
            NSString * name;
            if ([personMark length]<=0) {
                name = [MyClass getInstance].userName;
            }
            else
                name = [dict objectForKey:@"personShowName"];
            NSString * given = [dict objectForKey:@"given"];
            if ([type isEqualToString:@"plan"] || [type isEqualToString:@"deed"])
            {
                UITimeObjViewController* view = [[UITimeObjViewController alloc] initWithNibName:@"UITimeObjViewController" bundle:nil TimeObj:refId objType:type PersonName:name given:given];
                [self.navigationController pushViewController:view animated:YES];
                [view release];
            }
        }

    }
}
- (void)dealloc {
    self.arr =nil;
    self.allArr = nil;
//    self.dayArr=nil;
//    self.fullDayArr=nil;
    self.current_Day = nil;
    self.calendarView=nil;
    self.weekView=nil;
    [super dealloc];
}
@end
